package com.cn.jinl.service;

import com.cn.jinl.api.IRepairReportService;
import com.cn.jinl.conf.Config;
import com.cn.jinl.dao.RepairReportMapper;
import com.cn.jinl.dao.SysItemMapper;
import com.cn.jinl.domain.*;
import com.cn.jinl.utils.CommonUtil;
import com.cn.jinl.utils.QueryForm;
import com.cn.jinl.utils.msgSend.JsonReqClient;
import com.google.common.collect.Lists;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 * <p>
 * Description: RepairReportServiceImpl
 */
@Service
public class RepairReportServiceImpl implements IRepairReportService {

    @Autowired
    private RepairReportMapper repairReportMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    private SysItemMapper sysItemMapper;

    @Autowired
    Config config;
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    public List<RepairReport> getRepairReport(QueryForm queryForm) throws Exception {
        int count = repairReportMapper.getRepairReportCount(queryForm);
        if(count == 0){
            return Lists.newArrayList();
        }
        List<RepairReport> list = repairReportMapper.getRepairReport(queryForm);
        list.get(0).setCount(count);
        return list;
    }

    @Override
    public String addRepairReport(RepairReport repairReport) throws Exception {
        RepairReportExample reportExample = new RepairReportExample();
        reportExample.createCriteria().andEquipmentNumberEqualTo(repairReport.getEquipmentNumber()).andStatusNotEqualTo("2").andStatusNotEqualTo("3");
        List<RepairReport> list = repairReportMapper.selectByExample(reportExample);
        if (list.size()>0){
            return "该设备已存在报修信息";
        }

        if (null == repairReport){
            return "请输入报修信息";
        }

        String result = this.repairReportAddChange(repairReport);
        if (!"".equals(result)){
            return result;
        }

        String id = CommonUtil.generateRandomNum("repair_");
        repairReport.setId(id);

        repairReport.setStatus("0");
        repairReport.setCreateTime(new Date());

        //获取参数管理中的短信接收人
        QueryForm queryForm = new QueryForm();
        queryForm.setItemType("6");
        queryForm.setStatus("0");
        List<SysItem> sysItems = sysItemMapper.selectSysItems(queryForm);
        //新增成功后调取短信接口
        String itemAliases = sysItems.stream()
                .map(SysItem::getItemAlias)
                .collect(Collectors.joining(","))
                .replaceAll(",+$", "");
            JsonReqClient jsonReqClient = new JsonReqClient();
            String param =  dateFormat.format(repairReport.getCreateTime())+","+repairReport.getEquipmentName()+","+"[待受理]"+","+repairReport.getRepairName();
            String results = jsonReqClient.sendSmsBatch(config.sid, config.token, config.appid, config.templateId, param, itemAliases, "");
            redisTemplate.opsForValue().set(itemAliases, param, 120, TimeUnit.SECONDS);

            String remake="时间:"+dateFormat.format(repairReport.getCreateTime())+",设备号"+repairReport.getEquipmentName()+",状态:[待受理]"+",处理人:"+repairReport.getRepairName();
            repairReport.setRemake(remake);
        int count = repairReportMapper.insertSelective(repairReport);

        if (count < 1) {
            return "新增失败！";
        }
        return CommonUtil.outStr(count);
    }
    @Override
    public String cancelReport(RepairReport repairReport) {
        String id = repairReport.getId();

        if (StringUtils.isEmpty(id)){
            return "id is null";
        }
        if (StringUtils.isEmpty(repairReport.getCancelReason())){
            return "请输入取消理由";
        }
        RepairReportExample example = new RepairReportExample();
        example.createCriteria().andIdEqualTo(id);
        repairReport.setStatus("3");
        int count = repairReportMapper.updateByExampleSelective(repairReport,example);
        return CommonUtil.outStr(count);

    }

    @Override
    public String updateReport(RepairReport repairReport) {
        String id = repairReport.getId();

        if (StringUtils.isEmpty(id)){
            return "id is null";
        }
        //type为1的时候走报修受理 type为2的时候走维修受理
        String result="";
        if (repairReport.getType().equals("1")){
             result = this.ReportLegal(repairReport);
            repairReport.setStatus("1");
        }else if (repairReport.getType().equals("2")){
             result = this.ReportLegal2(repairReport);
            repairReport.setCompletionTime(new Date());
            repairReport.setStatus("2");
        }

        if (!"".equals(result)){
            return result;
        }
        RepairReportExample example = new RepairReportExample();
        example.createCriteria().andIdEqualTo(id);


        //获取参数管理中的短信接收人
        QueryForm queryForm = new QueryForm();
        queryForm.setItemType("6");
        queryForm.setStatus("0");
        List<SysItem> sysItems = sysItemMapper.selectSysItems(queryForm);
        //新增成功后调取短信接口
        String itemAliases = sysItems.stream()
                .map(SysItem::getItemAlias)
                .collect(Collectors.joining(","))
                .replaceAll(",+$", "");
        JsonReqClient jsonReqClient = new JsonReqClient();
        String param="";
        String remake="";
        if (repairReport.getType().equals("1")){
             param =dateFormat.format(repairReport.getAcceptanceTime())+","+repairReport.getEquipmentName()+","+"[维修中]"+","+repairReport.getAcceptanceName();
             remake="时间:"+dateFormat.format(repairReport.getAcceptanceTime())+",设备号"+repairReport.getEquipmentName()+",状态:[维修中]"+",处理人:"+repairReport.getAcceptanceName();

        }else if (repairReport.getType().equals("2")){
            param =dateFormat.format(repairReport.getCompletionTime())+","+repairReport.getEquipmentName()+","+"[维修完成]"+","+repairReport.getCompletionName();
             remake="时间:"+dateFormat.format(repairReport.getCompletionTime())+",设备号"+repairReport.getEquipmentName()+",状态:[维修完成]"+",处理人:"+repairReport.getCompletionName();

        }
        String results = jsonReqClient.sendSmsBatch(config.sid, config.token, config.appid, config.templateId, param, itemAliases, "");
        repairReport.setRemake(remake);
        int count = repairReportMapper.updateByExampleSelective(repairReport,example);
        if (count < 1) {
            return "修改失败！";
        }
        redisTemplate.opsForValue().set(itemAliases, param, 120, TimeUnit.SECONDS);

        return CommonUtil.outStr(count);
    }

    private String ReportLegal2(RepairReport repairReport) {
        String result = "";
        if (StringUtils.isBlank(repairReport.getMaintenanceContent())){
            result = "请输入维修内容";
            return result;
        }
        if (StringUtils.isBlank(repairReport.getMaintenanceName())){
            result = "请输入维修人";
            return result;
        }
        if (StringUtils.isBlank(repairReport.getMaintenanceName())){
            result = "请输入维修人";
            return result;
        }
        if (StringUtils.isBlank(repairReport.getRepairTime())){
            result = "请输入维修耗时";
            return result;
        }
        if (StringUtils.isBlank(repairReport.getCompletionName())){
            result = "请输入提交人";
            return result;
        }
        return result;
    }

    @Override
    public RepairReport getDetailById(RepairReport repairReport) {
        String id = repairReport.getId();
        RepairReport repairReports = repairReportMapper.selectByPrimaryKey(id);

        return repairReports;
    }

    private String ReportLegal(RepairReport repairReport) {
        String result = "";
        if (repairReport.getAcceptanceTime().equals("")){
            result = "请输入受理日期";
            return result;
        }
        if (StringUtils.isBlank(repairReport.getResponseTime())){
            result = "请输入响应时间";
            return result;
        }
        if (StringUtils.isBlank(repairReport.getAcceptanceName())){
            result = "请输入响应人";
            return result;
        }
        return result;
    }


    private String repairReportAddChange(RepairReport repairReport){

        String result = "";

        if (repairReport.getReportingTime().equals("")){
            result = "请输入报修日期";
            return result;
        }

        if (StringUtils.isBlank(repairReport.getRepairName())){
            result = "请输入报修人";
            return result;
        }
        return result;

    }
}
